package cn.tqfeiyang.smartadmin.business.organization.validator;

import cn.tqfeiyang.smartadmin.business.organization.entity.DepartmentEntity;
import cn.tqfeiyang.smartadmin.business.organization.mapper.DepartmentMapper;
import cn.tqfeiyang.smartadmin.commons.mybatis.IEntityValidator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import cn.hutool.core.lang.*;
import cn.tqfeiyang.smartadmin.commons.exception.*;
import cn.tqfeiyang.smartadmin.commons.toolbox.*;

/**
 * 部门实体验证器
 *
 * @author tqfeiyang
 * @since 2024-10-18
 */
@Component
public class DepartmentValidator implements IEntityValidator<DepartmentEntity> {

    /**
     * 部门映射接口
     */
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 验证实体数据
     *
     * @param entity 部门实体
     * @param creating 是否是添加
     */
    @Override
    public void validate(DepartmentEntity entity, boolean creating) {
        if (StringUtils.isNotBlank(entity.getName())) {
            // 检查名称是否重复？
            if (departmentMapper.checkNameExists(entity.getName(), entity.getDepartmentId())) {
                throw new BusinessException("名称重复({})", entity.getName());
            }
        }
    }

    /**
     * 删除前检查
     *
     * @param entity 部门实体
     */
    @Override
    public void beforeDelete(DepartmentEntity entity) {
        // 检查是否有员工存在？
        if (departmentMapper.countOfEmployeesByDepartmentId(entity.getDepartmentId()) > 0) {
            throw new BusinessException("有员工存在，不能删除");
        }
    }

    /**
     * 删除后处理
     *
     * @param entity 部门实体
     */
    @Override
    public void afterDelete(DepartmentEntity entity) {
    }
}